package com.timmy.google_play.proxy;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Timmy on 2016/12/10.
 * 线程池代理,替ThreadPool 做一些操作，对相关方法增强
 */

public class ThreadPoolProxy {

    ThreadPoolExecutor mExecutor;
    private int mCorePoolSize;
    private int mMaximumPoolSize;

    public ThreadPoolProxy(int corePoolSize) {
        mCorePoolSize = corePoolSize;
        mMaximumPoolSize = corePoolSize;
    }

    private void initThreadPoolExecutor() {
        if (mExecutor == null || mExecutor.isShutdown() || mExecutor.isTerminated()) {
            synchronized (ThreadPoolProxy.class) {
                if (mExecutor == null || mExecutor.isShutdown() || mExecutor.isTerminated()) {

                    long                     keepAliveTime = 3000;  //保持时间
                    TimeUnit                 unit          = TimeUnit.MILLISECONDS;
                    BlockingQueue<Runnable>  workQueue     = new LinkedBlockingDeque<>();   //任务队列
                    ThreadFactory            threadFactory = Executors.defaultThreadFactory();  //线程工厂
                    RejectedExecutionHandler handler       = new ThreadPoolExecutor.DiscardPolicy();  //异常捕获器

                    mExecutor = new ThreadPoolExecutor( mCorePoolSize,
                                                        mMaximumPoolSize,
                                                        keepAliveTime,
                                                        unit,
                                                        workQueue,
                                                        threadFactory,
                                                        handler);
                }
            }
        }
    }

    /**
     * 提交任务和执行任务的区别
     * submit ---> 有返回值
     * excute ---> 没有返回值
     *
     *
     *  submit 返回回来的Future对象作用
     *      描述异步任务执行的结果的
     */


    /**
     * 提交任务
     */
    public Future<?> submit(Runnable task) {
        initThreadPoolExecutor();

        Future<?> future = mExecutor.submit(task);
        return future;
    }

    /**
     * 执行任务
     */
    public void execute(Runnable task) {

        initThreadPoolExecutor();
        mExecutor.execute(task);
    }

    /**
     * 移除任务
     */
    public void remove(Runnable task) {

        initThreadPoolExecutor();
        mExecutor.remove(task);
    }
}